package com.shadow.istio.client.config;

import com.shadow.istio.api.HelloWorldGrpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 *  * gRPC Client的配置——启动、建立channel、获取stub、关闭等
 *  * 需要注册为Spring Bean
 */
@Slf4j
@Component
public class GrpcClientConfiguration {
    // grpc server 端地址
    @Value("${server-host}")
    private String host;
    // grpc server 端端口
    @Value("${server-port}")
    private int port;

    private ManagedChannel channel;
    private HelloWorldGrpc.HelloWorldBlockingStub stub;

    public void start(){
        // 开启 channel
        channel = ManagedChannelBuilder.forAddress(host,port).usePlaintext().build();
        // 通过 channel 获取到服务器端 stub
        stub = HelloWorldGrpc.newBlockingStub(channel);
        log.info("grpc client startd, server address: {}:{}", host, port);
    }

    public void shutdown() throws InterruptedException {
        // 调用shutdown方法后等待1秒关闭channel
        channel.shutdown().awaitTermination(1, TimeUnit.SECONDS);
        log.info("gRPC client shut down successfully.");
    }

    public HelloWorldGrpc.HelloWorldBlockingStub getStub() {
        return this.stub;
    }


}
